﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using fbasync.web.Data;

namespace fbasync.web.Controls.TemplateEditor
{
    public partial class StoryTemplateBundleItem : BaseUserControl
    {
        public string ReadOnlyTextBoxCssClass { get; set; }
        public string ReadModeShortTextboxCssClass { get; set; }
        public string EditModeTextBoxCssClass { get; set; }
        public string EditModeShortTextBoxCssClass { get; set; }
        public string SelectedTabCssClass { get; set; }
        public string UnSelectedTabCssClass { get; set; }

        public string TemplateContainerCssClass 
        {
            get { return uiTemplateContainer.Attributes["class"]; }
            set { uiTemplateContainer.Attributes["class"] = value; }
        }

        public int InternalId
        {
            get { return ((int?)ViewState["InternalId"]).GetValueOrDefault(Consts.UnknownUniqueBundleId); }
            set { ViewState["InternalId"] = value; }
        }

        public long BundleId
        {
            get 
            {
                long result;

                if (!long.TryParse(uiBundleId.Text, out result)) result = Consts.UnknownBundleId;

                return result;
            }
        }

        public bool IsChanged
        {
            get 
            {
                if (Consts.UnknownUniqueBundleId == InternalId) return false;

                return TemplateEditorDataAccess.IsBundleChanged(InternalId); 
            }
        }

        public bool IsNew
        {
            get { return Consts.UnknownBundleId == BundleId; }
        }

        protected override void OnPreRender(EventArgs e)
        {
            InitControls();

            base.OnPreRender(e);
        }

        private void InitControls()
        {
            bool isChanged = IsChanged;

            uiOneLineToolbar.Visible = isChanged;
            uiShortStoryToolbar.Visible = isChanged;

            bool isEditingMode = TemplateEditorDataAccess.IsEditingMode();

            uiReadToolbar.Visible = !isEditingMode;
            uiAppEventsContainer.Visible = isEditingMode;

            if (isEditingMode) InitAppEventsList();
           
            InitTabControls();
        }

        private void InitAppEventsList()
        {
            ApplicationInfo currentApp = ApplicationManager.CurrentApplication;

            if (currentApp.Events == null) uiAppEventsContainer.Visible = false;
            else
            {
                uiAppEventsContainer.Visible = true;
                uiAppEventsList.Items.Clear();

                uiAppEventsList.Items.Add(new ListItem(GetString("infoUnassigned"), String.Empty));

                foreach (ApplicationEvent appEvent in currentApp.Events)
                {
                    uiAppEventsList.Items.Add(new ListItem(appEvent.Text, appEvent.Value));
                }

                
                for (int itemIndex = 0; itemIndex < uiAppEventsList.Items.Count; itemIndex++)
                {
                    if (uiAppEventsList.Items[itemIndex].Value.Equals(uiNameTextBox.Text))
                    {
                        uiAppEventsList.SelectedIndex = itemIndex;
                        break;
                    }
                }
            }
        }

        private void InitTabControls()
        {
            uiFullStoryTitle.Attributes["onclick"] =
                String.Format("TemplateEditor.SelectTab('{0}', '{1}', ['{2}'], ['{3}', '{4}'], '{5}', '{6}')", 
                uiFullTemplateTab.ClientID, 
                uiCurrentTab.ClientID,
                uiFullStoryTitle.ClientID,
                uiOneLineStoriesTitle.ClientID,
                uiShortStoriesTitle.ClientID,
                SelectedTabCssClass,
                UnSelectedTabCssClass);
            uiOneLineStoriesTitle.Attributes["onclick"] =
                String.Format("TemplateEditor.SelectTab('{0}', '{1}', ['{2}'], ['{3}', '{4}'], '{5}', '{6}')", 
                uiOneLineTemplatesTab.ClientID, 
                uiCurrentTab.ClientID,
                uiOneLineStoriesTitle.ClientID,
                uiFullStoryTitle.ClientID,
                uiShortStoriesTitle.ClientID,
                SelectedTabCssClass,
                UnSelectedTabCssClass);
            uiShortStoriesTitle.Attributes["onclick"] =
                String.Format("TemplateEditor.SelectTab('{0}', '{1}', ['{2}'], ['{3}', '{4}'], '{5}', '{6}')", 
                uiShortStoryTemplateTab.ClientID, 
                uiCurrentTab.ClientID,
                uiShortStoriesTitle.ClientID,
                uiFullStoryTitle.ClientID,
                uiOneLineStoriesTitle.ClientID,
                SelectedTabCssClass,
                UnSelectedTabCssClass);

            uiFullTemplateTab.Style["display"] = "none";
            uiOneLineTemplatesTab.Style["display"] = "none";
            uiShortStoryTemplateTab.Style["display"] = "none";

            uiOneLineStoriesTitle.CssClass = UnSelectedTabCssClass;
            uiFullStoryTitle.CssClass = UnSelectedTabCssClass;
            uiShortStoriesTitle.CssClass = UnSelectedTabCssClass;

            if (uiCurrentTab.Value == uiOneLineTemplatesTab.ClientID)
            {
                uiOneLineTemplatesTab.Style["display"] = "block";
                uiOneLineStoriesTitle.CssClass = SelectedTabCssClass;
            }
            else if (uiCurrentTab.Value == uiShortStoryTemplateTab.ClientID)
            {
                uiShortStoryTemplateTab.Style["display"] = "block";
                uiShortStoriesTitle.CssClass = SelectedTabCssClass;
            }
            else
            {
                uiFullTemplateTab.Style["display"] = "block";
                uiFullStoryTitle.CssClass = SelectedTabCssClass;
            }
        }

        protected void AppEventsList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (null != uiAppEventsList.SelectedItem)
            {
                uiNameTextBox.Text = uiAppEventsList.SelectedItem.Value;
            }
        }

        public void AssignTemplateBundle(TemplateEditorDataSet.StoryTemplateBundleRow bundleRow)
        {
            InternalId = bundleRow.UniqueId;

            bool isChanged = IsChanged;

            uiNameTextBox.Text = bundleRow.IsNameNull() ? String.Empty : bundleRow.Name;
            uiNameTextBox.CssClass = isChanged ? EditModeTextBoxCssClass : ReadOnlyTextBoxCssClass;
            uiNameTextBox.ReadOnly = !isChanged;

            uiBundleId.Text = Consts.UnknownBundleId == bundleRow.BundleId ? GetString("infoUnassigned") : bundleRow.BundleId.ToString();
            uiCreatedDate.Text = Consts.UnknownBundleId == bundleRow.BundleId ? GetString("infoUnknowDate") : bundleRow.Created.ToString();

            StoryTemplate fullStoryTemplate = new StoryTemplate();

            fullStoryTemplate.template_title = bundleRow.IsFullStoryTitleNull() ? String.Empty : bundleRow.FullStoryTitle;
            fullStoryTemplate.template_body = bundleRow.IsFullStoryBodyNull() ? String.Empty : bundleRow.FullStoryBody;

            uiFullStoryTemplate.AssignStoryTemplate(fullStoryTemplate);

            AssignOneLineStories(bundleRow.UniqueId);
            AssignShortStories(bundleRow.UniqueId);

            uiEditToolbar.Style[HtmlTextWriterStyle.Display] = isChanged ? "inline" : "none";

            uiTemplateContainer.Attributes["class"] = isChanged ? "editStoryTemplateBundleTable" : "storyTemplateBundleTable";
        }

        private void AssignShortStories(int bundleUniqueId)
        {
            uiShortStories.DataSource = TemplateEditorDataAccess.GetBundleShortStores(bundleUniqueId);
            uiShortStories.DataBind();
        }

        private void AssignOneLineStories(int bundleUniqueId)
        {
            uiOneLineStories.DataSource = TemplateEditorDataAccess.GetBundleOneLineStores(bundleUniqueId);
            uiOneLineStories.DataBind();
        }

        protected void OneLineStories_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ((StoryTemplateItem)e.Item.FindControl("uiOneLineStoryTemplate")).AssignStoryTemplate((TemplateEditorDataSet.OneLineTemplateRow)((DataRowView)e.Item.DataItem).Row);
        }

        protected void ShortStories_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ((StoryTemplateItem)e.Item.FindControl("uiShortStoryTemplate")).AssignStoryTemplate((TemplateEditorDataSet.ShortStoryTemplateRow)((DataRowView)e.Item.DataItem).Row);
        }

        private void AssignControlValues()
        {
            TemplateEditorDataSet.StoryTemplateBundleRow editingRow = TemplateEditorDataAccess.DataSet.StoryTemplateBundle.FindByUniqueId(InternalId);

            if (null == editingRow) return;

            if (String.IsNullOrEmpty(uiNameTextBox.Text)) editingRow.SetNameNull();
            else
            {
                editingRow.Name = uiNameTextBox.Text;
            }

            if (String.IsNullOrEmpty(uiFullStoryTemplate.Title)) editingRow.SetFullStoryTitleNull();
            else
            {
                editingRow.FullStoryTitle = uiFullStoryTemplate.Title;
            }

            if (String.IsNullOrEmpty(uiFullStoryTemplate.Body)) editingRow.SetFullStoryBodyNull();
            else
            {
                editingRow.FullStoryBody = uiFullStoryTemplate.Body;
            }

            AssignOneLineControls();
            AssignShortStoryControls();
        }

        private void AssignOneLineControls()
        {
            foreach (RepeaterItem oneLineItem in uiOneLineStories.Items)
            {
                ((StoryTemplateItem)oneLineItem.FindControl("uiOneLineStoryTemplate")).AssignOneLineControls(InternalId);
            }
        }

        private void AssignShortStoryControls()
        {
            foreach (RepeaterItem shortStoryItem in uiShortStories.Items)
            {
                ((StoryTemplateItem)shortStoryItem.FindControl("uiShortStoryTemplate")).AssignShortStoryControls(InternalId);
            }
        }

        protected void AddOneLineStoryButton_Click(object sender, EventArgs e)
        {
            AssignOneLineControls();

            TemplateEditorDataAccess.CreateNewOneLineStory(InternalId);

            AssignOneLineStories(InternalId);
        }

        protected void AddShortStoryButton_Click(object sender, EventArgs e)
        {
            AssignShortStoryControls();

            TemplateEditorDataAccess.CreateNewShortStory(InternalId);

            AssignShortStories(InternalId);
        }

        protected void DeleteOneLineStoryButton_Click(object sender, EventArgs e)
        {
            AssignOneLineControls();

            foreach (RepeaterItem oneLineItem in uiOneLineStories.Items)
            {
                ((StoryTemplateItem)oneLineItem.FindControl("uiOneLineStoryTemplate")).DeleteOneLineIfChecked(InternalId);
            }

            AssignOneLineStories(InternalId);
        }

        protected void DeleteShortStoryButton_Click(object sender, EventArgs e)
        {
            AssignShortStoryControls();

            foreach (RepeaterItem shortStoryItem in uiShortStories.Items)
            {
                ((StoryTemplateItem)shortStoryItem.FindControl("uiShortStoryTemplate")).DeleteShortStoryIfChecked(InternalId);
            }

            AssignShortStories(InternalId);
        }

        protected void RegisterTemplateBundleCompleted(object sender, AsyncCompletedEventArgs<long> e)
        {
            if (null == e.Error)
            {
                ApplicationTemplates.Instance.ApplicationKey = String.Empty; // We need to reread templates to get the new bundle id
                ApplicationTemplates.Instance.InitControls();
                
                TemplateEditorDataAccess.AcceptBundleChanges(e.Result, InternalId);

                TemplateEditorMenu.Instance.InitControls();
            }
            else
            {
                ExceptionHandler.HandleException(e.Error);
            }
        }

        private void StoreTemplateBundle()
        {
            Global.Connection.RegisterTemplateBundleCompleted += RegisterTemplateBundleCompleted;

            StoryTemplateBundle newBundle = TemplateEditorDataAccess.GetStoryTemplateBundle(InternalId);

            if (null == newBundle.OneLineStories)
            {
                newBundle.OneLineStories = new List<StoryTemplate>();
                newBundle.OneLineStories.Add(new StoryTemplate() { template_title = TemplateEditorDataAccess.DefaultOneLineTitle });
            }

            Global.Connection.RegisterTemplateBundleAsync(newBundle);
        }

        private bool IsInputValid()
        {
            if (String.IsNullOrEmpty(uiNameTextBox.Text))
            {
                ExceptionHandler.HandleException(new Exception(GetString("errorEmptyName")));

                return false;
            }

            int uniqueId = TemplateEditorDataAccess.GetBundleByName(uiNameTextBox.Text);

            if ((Consts.UnknownInternalId!= uniqueId) && (uniqueId != InternalId))
            {
                ExceptionHandler.HandleException(new Exception(GetString("errorNameExists")));

                return false;
            }

            return true;
        }

        protected void SaveBundleButton_Click(object sender, EventArgs e)
        {
            if (IsInputValid())
            {
                AssignControlValues();

                if (IsNew) StoreTemplateBundle();
                else
                {
                    if (IsChanged)
                    {
                        DeleteBundle(true);
                        StoreTemplateBundle();
                    }
                }
            }
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            TemplateEditorDataAccess.CancelBundleEditing(InternalId);
            ApplicationTemplates.Instance.InitControls();
        }

        private void DeleteBundle(bool onlyFromFb)
        {
            long bundleId = BundleId;

            if (Consts.UnknownBundleId == bundleId)
            {
                TemplateEditorDataAccess.DeleteStoryTemplateBundle(InternalId);
                ApplicationTemplates.Instance.InitControls();
            }
            else
            {
                Global.Connection.DeactivateTemplateBundleCompleted +=
                    delegate
                    {
                        if (!onlyFromFb)
                        {
                            TemplateEditorDataAccess.DeleteStoryTemplateBundle(InternalId);
                            ApplicationTemplates.Instance.InitControls();
                        }
                    };
                Global.Connection.DeactivateTemplateBundleAsync(bundleId, null);
            }
        }

        protected void DeleteBundle_Click(object sender, EventArgs e)
        {
            DeleteBundle(false);
        }

        protected void EditBundle_Click(object sender, EventArgs e)
        {
            TemplateEditorDataAccess.SetEditMode(BundleId);

            ApplicationTemplates.Instance.InitControls();
            TemplateEditorMenu.Instance.InitControls();
        }
    }
}